package model

import (
	"common/config"
	"common/helper"
	myUserHelp "common/userHelp"
	"errors"
	"fmt"
	"member/contrib/validator"
	"time"

	"github.com/valyala/fasthttp"
)

func Recharge(fctx *fasthttp.RequestCtx, prefix, fid, amount, flag string) (PaymentDepositResp, error) {

	res := PaymentDepositResp{}

	uid := GetUidFromToken(fctx)

	//add test
	//uid = "24652593"

	if uid == "" {
		return res, errors.New(helper.AccessTokenExpires)
	}

	if myUserHelp.GetMemberState(uid) == 2 {
		return res, errors.New(helper.Blocked)
	}

	p, err := CachePayFactory(fid)
	if err != nil {
		return res, errors.New(helper.ChannelNotExist)
	}

	res, err = Pay(fctx, meta.Program, uid, p, amount, flag)
	if err != nil {
		helper.SqlSelectErrLog("deposit username[%d] args: %s, ts: %s  \n",
			myUserHelp.GetMemberState(uid), fctx.PostArgs().String(), time.Now().Format("2006-01-02 15:04:05"))
		return res, err
	}

	return res, nil
}

// Pay 发起支付公共入口
func Pay(fctx *fasthttp.RequestCtx, prefix string, uid string, p TblPayFactory, amount, flag string) (PaymentDepositResp, error) {

	data := PaymentDepositResp{}

	//payment, ok := thirdFuncCb[p.Fid]
	//if !ok {
	//	return data, errors.New(helper.NoPayChannel)
	//}

	// 检查存款金额是否符合范围
	a, ok := validator.CheckFloatScope(amount, p.Fmin, p.Fmax)
	if !ok {
		return data, errors.New(helper.AmountOutRange)
	}

	// 检查订单提交次数是否超过限制
	if !CheckOrderLimit(uid) {
		return data, errors.New(helper.LimitExceed)
	}

	// 测试号
	if myUserHelp.GetMemberTester(uid) == 2 {
		return data, errors.New(helper.AmountOutRange)
	}

	amount = a.String()
	// 生成我方存款订单号
	orderId := helper.GenId() + "@" + prefix
	payment := &thirdEpay{}
	var err error
	if p.Fid == "1" {
		data, err = payment.CreateEpayOrder(amount, orderId, uid, p)
	}
	if p.Fid == "3" {
		data, err = CreateJeePayOrder(amount, orderId, uid, p)
	}
	if p.Fid == "5" {
		data, err = CreateCePayOrder(amount, orderId, uid, p)
	}

	if p.Fid == "7" {
		data, err = CreateBetcatPayOrder(amount, orderId, uid, p)
	}

	if p.Fid == "9" {
		data, err = CreateU2CPayOrder(amount, orderId, uid, p)
	}

	if p.Fid == "11" {
		data, err = CreatePay4zOrder(amount, orderId, uid, p)
	}

	if err == fmt.Errorf(helper.CPFError) {
		helper.SqlSelectErrLog("Pay  payment.Pay err:%s", fmt.Errorf(helper.CPFError))
		return data, fmt.Errorf(helper.CPFError)
	}

	if err != nil {
		helper.SqlSelectErrLog("Pay  payment.Pay err:%s", err)
		return data, err
	}

	ParentId := myUserHelp.GetProxyParentId(uid)
	d := TblDeposit{
		Id:         orderId,
		Oid:        orderId,
		Uid:        uid,
		ParentId:   ParentId,
		Fid:        p.Fid,
		Fname:      p.Name,
		Amount:     amount,
		ConfirmUid: "0",
		State:      DepositConfirming,
		CreatedAt:  fctx.Time().Unix(),
		ConfirmAt:  fctx.Time().Unix(),
		Discount:   0,
		IsFirst:    0,
		IsReceived: 0,
		Hidden:     0,
	}

	query, _, _ := dialect.Insert("tbl_deposit").Rows(d).ToSQL()
	_, errExec := GetMasterDBInstance().Exec(query)
	if errExec != nil {
		helper.SqlErrLog("[Pay]:insert sql: %s reason:%s", query, errExec.Error())
		return data, errors.New(helper.DBErr)
	}

	return data, nil
}

func CheckOrderLimit(uid string) bool {
	// 生成订单提交次数记录的 Redis 键名
	key := fmt.Sprintf("order_count:%s", uid)

	// 从 Redis 中获取订单提交次数
	countCmd := meta.MerchantRedis.Incr(ctx, key)
	count, err := countCmd.Result()
	if err != nil {
		helper.InfoLog("增加订单提交次数失败：%s", err.Error())
		return false
	}

	// 设置过期时间为 1 分钟
	if count == 1 {
		expireCmd := meta.MerchantRedis.Expire(ctx, key, time.Minute)
		if err := expireCmd.Err(); err != nil {
			helper.InfoLog("设置过期时间失败：%s", err.Error())
			return false
		}
	}

	// 如果订单提交次数超过限制，则返回 false
	if count >= int64(config.GetGameCfgInt(config.CfgDepositCountLimit)) {
		return false
	}

	return true
}
